"""
Case Type   : cm
Case Name   : cm_server查看cm_server版本和帮助信息
Create At   : 2024-07
Owner       : haomeng
Description :
    1、查看集群状态
    2、查看cm_server版本信息
    3、查看cm_server帮助信息
Expect      :
    1、集群所有节点状态正常，显示Normal
    2、cm_server版本信息查看成功
    3、cm_server帮助信息查看成功
History     :
"""

import os
import re
import unittest

from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro

Primary_SH = CommonSH('PrimaryDbUser')


@unittest.skipIf(3 != Primary_SH.get_node_num(), '需1主2备环境，否则不执行')
class CmCtl(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.comsh = CommonSH('PrimaryDbUser')
        self.pri_user = Node('PrimaryDbUser')
        self.constant = Constant()

    def test_cm(self):
        text = '----step1:查看集群状态; expect:集群状态正常,DN主在节点1----'
        self.log.info(text)

        status = self.comsh.exec_cm_ctl('query', '-Cv')
        self.log.info(status)
        self.assertIn("cluster_state   : Normal", status)

        text = '----step2:查看cm_server版本信息; expect:cm_server版本信息查看成功----'
        self.log.info(text)

        version_list = ['-V', '--version']
        for v in version_list:
            res = self.pri_user.sh(f'source {macro.DB_ENV_PATH};cm_server {v}').result()
            self.log.info(res)
            self.assertTrue(re.match('cm_server.*compiled.*',res), '版本信息检查失败')


        text = '------step3:查看cm_server帮助信息; expect:cm_server帮助信息查看成功------'
        self.log.info(text)

        help_list = ['-?', '-h', '--help']
        help_result = 'cm_server is a utility to arbitrate an instance.\n\n' \
                      'Usage:\n  ' \
                      'cm_server\n  ' \
                      'cm_server 0\n  ' \
                      'cm_server 1\n  ' \
                      'cm_server 2\n  ' \
                      'cm_server 3\n\n' \
                      'Common options:\n  ' \
                      '-?, -h, --help         show this help, then exit\n  ' \
                      '-V, --version          output version information, then exit\n\n' \
                      'location of the log information options:\n  ' \
                      '0                      LOG_DESTION_FILE\n  ' \
                      '1                      LOG_DESTION_SYSLOG\n  ' \
                      '2                      LOG_DESTION_FILE\n  ' \
                      '3                      LOG_DESTION_DEV_NULL'
        for h in help_list:
            res = self.pri_user.sh(f'source {macro.DB_ENV_PATH};cm_server {h}').result()
            self.log.info(res)
            self.assertEqual(res, help_result, '帮助信息查询失败')

    def tearDown(self):
        self.log.info('-----No need to clean-----')
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
